<?php
class NewsController extends AdminAppController
{
    public $uses = array('Admin.News');

    public $paginate = array(
        //'fields' => array('Work.id', 'Work.title', 'Work.service_id', 'Work.created', 'Work.updated'),
        'limit' => 25,
        'order' => array(
            'News.priority' => 'desc',
            'News.updated' => 'desc'
        )
    );

    public function index()
    {
        $data = $this->paginate('News');
        $categories = $this->News->Category->find('list');
        $this->set(compact('categories', 'data'));
    }

    public function add()
    {
        if ($this->request->is('post')) {
            try {
                $this->News->saveNews($this->request->data);
                $this->redirect(array('action' => 'index'));
                $this->Session->setFlash(__('The News has been saved'));
            } catch (Exception $e) {
                $validationErrors = $this->News->validationErrors;
                $this->set(compact('validationErrors'));
                $this->Session->setFlash($e->getMessage());
            }
        }
        $newsCategories = $this->News->Category->find('list');
        $this->set(compact('newsCategories'));
    }

    public function edit($id=null)
    {
        $news = $this->News->getNews($id);
        if ($this->request->is('get')) {
            $this->request->data = $news;
        } else {
            try {
                $isUpdate = true;
                $this->News->saveNews($this->request->data, $isUpdate, $news);
                $this->redirect(array('action' => 'index'));
                $this->Session->setFlash(__('The News has been saved'));
            } catch (Exception $e) {
                $this->request->data = $this->_mergeData($news);
                $validationErrors = $this->News->validationErrors;
                $this->set(compact('validationErrors'));
                $this->Session->setFlash($e->getMessage());
            }
        }
        $newsCategories = $this->News->Category->find('list');
        $this->set(compact('newsCategories'));
    }

    public function delete($id=null)
    {
        if ($id == null) {
            $this->redirect('/');
        }
        $data = array(
            'Work' => array(
                'id' => $id,
                'is_deleted' => 1
            )
        );
        $this->Work->save($data);
        $this->redirect('/admin/news');
    }

    public function _mergeData($case)
    {
        $request = $this->request->data['Admin']['News'];
        return $this->request->data; 
    }
}
